// geomUtils.js
function getPointsFromBBox(bbox) {
    let x0 = bbox[0],
        y0 = bbox[1],
        x1 = bbox[2],
        y1 = bbox[3];
    let points = [
        { x: x0, y: y0 },
        { x: x1, y: y0 },
        { x: x1, y: y1 },
        { x: x0, y: y1 }
    ];
    return points;
}

function getPointsFromSegs(segs) {
    let points = [];
    for (let i = 0; i < segs.length; i += 1) {
        let seg = segs[i];
        for (let j = 0; j < seg.length; j += 2) {
            let point = {
                x: seg[j],
                y: seg[j + 1]
            };
            points.push(point);
        }
    }
    return points;
}

function getPointsFromSeg(seg) {
    let points = [];
    for (let j = 0; j < seg.length; j += 2) {
        let point = {
            x: seg[j],
            y: seg[j + 1]
        };
        points.push(point);
    }
    return points;
}

function getPointsLT(points) {
    let pt_tl = { x: points[0].x, y: points[0].y };
    for (let i = 1; i < points.length; i++) {
        let pt = points[i];
        if (pt.x < pt_tl.x) {
            pt_tl.x = pt.x;
        }
        if (pt.y < pt_tl.y) {
            pt_tl.y = pt.y;
        }
    }
    return pt_tl;
}

function getPointsRB(points) {
    let pt_rb = { x: points[0].x, y: points[0].y };
    for (let i = 1; i < points.length; i++) {
        let pt = points[i];
        if (pt.x > pt_rb.x) {
            pt_rb.x = pt.x;
        }
        if (pt.y > pt_rb.y) {
            pt_rb.y = pt.y;
        }
    }
    return pt_rb;
}

// 计算多边形的边界框
function calculatePolygonBounds(points) {
    var minX = points.reduce((min, point) => Math.min(min, point.x), points[0].x);
    var maxX = points.reduce((max, point) => Math.max(max, point.x), points[0].x);
    var minY = points.reduce((min, point) => Math.min(min, point.y), points[0].y);
    var maxY = points.reduce((max, point) => Math.max(max, point.y), points[0].y);
    return {
        left: minX,
        top: minY,
        right: maxX,
        bottom: maxY,
        width: maxX - minX,
        height: maxY - minY
    };
}

// 平移后polygon对象的points位置不对，需要根据topleft，重新计算各个点坐标
function calcPolyPoints(points, tl_pt) {
    // 获得points的左上角坐标
    let tl = { x: points[0].x, y: points[0].y };
    for (let i = 1; i < points.length; i++) {
        let pt = points[i];
        if (pt.x < tl.x) {
            tl.x = pt.x;
        }
        if (pt.y < tl.y) {
            tl.y = pt.y;
        }
    }

    // 计算offset并重新给points复制
    let offsetx = tl_pt.x - tl.x;
    let offsety = tl_pt.y - tl.y;
    let new_points = [];
    for (let i = 0; i < points.length; i++) {
        let pt = { x: points[i].x + offsetx, y: points[i].y + offsety };
        new_points.push(pt);
    }

    return new_points;
}

export { getPointsFromBBox, getPointsFromSegs, getPointsFromSeg, getPointsLT, getPointsRB, calculatePolygonBounds, calcPolyPoints };
